package com.example.weight.greenSeasons.compost;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.weight.R;
import com.example.weight.config.Config;
import com.hjq.bar.OnTitleBarListener;
import com.hjq.bar.TitleBar;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.InputType;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import net.cachapa.expandablelayout.ExpandableLayout;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class TonBagCompletion extends AppCompatActivity {

    //用户、抄表人
    private String username, factory;
    private int width;

    private ExpandableLayout expandable_1, expandable_2, expandable_3, expandable_4,
                             expandable_5, expandable_6, expandable_7, expandable_8;
    private Button btn_1, btn_2, btn_3, btn_4, btn_5, btn_6, btn_7, btn_8;

    @SuppressLint("SetTextI18n")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ton_bag_completion);

        Intent previousIntent = getIntent();
        username = previousIntent.getStringExtra("name");
        factory = previousIntent.getStringExtra("factory");

        TitleBar titleBar = findViewById(R.id.titleBar);
        titleBar.setOnTitleBarListener(new OnTitleBarListener() {
            @Override
            public void onLeftClick(View v) {finish();}

            @Override
            public void onTitleClick(View v) {}

            @Override
            public void onRightClick(View v) {}
        });

        TextView dateEdit = findViewById(R.id.worm_incoming_incomeDate);
        Calendar calendar=Calendar.getInstance();
        Integer year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH)+1; //第一个月从0开始，所以得到月份＋1
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        dateEdit.setText(year+"-"+month+"-"+day);

        expandable_1 = findViewById(R.id.expandable_1); expandable_2 = findViewById(R.id.expandable_2);
        expandable_3 = findViewById(R.id.expandable_3); expandable_4 = findViewById(R.id.expandable_4);
        expandable_5 = findViewById(R.id.expandable_5); expandable_6 = findViewById(R.id.expandable_6);
        expandable_7 = findViewById(R.id.expandable_7); expandable_8 = findViewById(R.id.expandable_8);
        btn_1 = findViewById(R.id.button1); btn_2 = findViewById(R.id.button2); btn_3 = findViewById(R.id.button3);
        btn_4 = findViewById(R.id.button4); btn_5 = findViewById(R.id.button5); btn_6 = findViewById(R.id.button6);
        btn_7 = findViewById(R.id.button7); btn_8 = findViewById(R.id.button8);
        List<Integer> linearLayoutIds = new ArrayList<>();
        linearLayoutIds.add(R.id.compost_dundaiwangchengliang_chuyujiliao);
        linearLayoutIds.add(R.id.compost_dundaiwangchengliang_duifeijinliao);
        linearLayoutIds.add(R.id.compost_dundaiwangchengliang_duifeichuliao);
        linearLayoutIds.add(R.id.compost_dundaiwangchengliang_chushengliao);
        linearLayoutIds.add(R.id.compost_dundaiwangchengliang_chuyugangpeihejinchu);
        linearLayoutIds.add(R.id.compost_dundaiwangchengliang_chuyugangjinchu);
        linearLayoutIds.add(R.id.compost_dundaiwangchengliang_duifeigangjin);
        linearLayoutIds.add(R.id.compost_dundaiwangchengliang_duifeigangchu);
        List<String> projects = new ArrayList<>();
        projects.add("厨余进料未完成量");   projects.add("堆肥进料未完成量");
        projects.add("堆肥出料未完成量");   projects.add("除生料进料配合进、出料");
        projects.add("厨余岗工作时间外配合进、出吨袋工作时间");
        projects.add("厨余岗进、出吨袋本职工作额外完成量");
        projects.add("堆肥岗进料额外完成量"); projects.add("堆肥岗出料额外完成量");

        WindowManager wManager = (WindowManager) getSystemService(this.WINDOW_SERVICE);
        width = wManager.getDefaultDisplay().getWidth() * 3 / 10;

        for (int i = 0; i < projects.size(); i++) {
            // 项目所在LinearLayout
            String project = projects.get(i);
            LinearLayout linearLayout = findViewById(linearLayoutIds.get(i));
            // 根据项目 获取姓名列表
            RequestQueue queue = Volley.newRequestQueue(this);
            String url = Config.url + "/sjq/sjqCompletionOfCompostTonbag/getAllName";
            StringRequest setSysNameRequest = new StringRequest(Request.Method.POST, url,
                    new com.android.volley.Response.Listener<String>() {
                        @Override
                        public void onResponse(String response) {
                            try {
                                JSONObject jsonObject = new JSONObject(response);
                                if (!jsonObject.isNull("data")) {
                                    JSONArray jsonArray = jsonObject.getJSONArray("data");
                                    List<String> names = new ArrayList<>();
                                    for (int j = 0; j < jsonArray.length(); j++){
                                        names.add(jsonArray.getString(j));
                                    }
                                    initNames(linearLayout, names, project);
                                } else {
                                    Toast.makeText(TonBagCompletion.this,
                                            "该岗位未设置处理员", Toast.LENGTH_SHORT).show();
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(TonBagCompletion.this,
                            "获取信息失败 " + error.getMessage(), Toast.LENGTH_SHORT).show();
                }
            }) {
                @Override
                protected Map<String, String> getParams() {
                    Map<String, String> map = new HashMap<>();
                    map.put("entry", project);
                    map.put("factory", factory);
                    return map;
                }
            };
            setSysNameRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                    DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
            queue.add(setSysNameRequest);
        }
    }

    private void initNames (LinearLayout layout, List<String> names, String project) {
        for (String name : names) {
            LinearLayout ll = new LinearLayout(TonBagCompletion.this);
            //        ll.setPadding(20, 0, 0, 0);
            //该layoutParams为包裹在外层Linearyout父布局的类型。
            ViewGroup.MarginLayoutParams margin = new
                    LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
            //设置margin值
            margin.setMargins(0, 5, 0, 0);
            //给需要设置的Linearyout重新设置layoutParams属性
            ll.setLayoutParams(margin);

            TextView tv = new TextView(TonBagCompletion.this);
            tv.setText(name);
            tv.setTextColor(Color.parseColor("#000000"));
            EditText et = new EditText(TonBagCompletion.this);
            et.setWidth(width);
            et.setInputType(InputType.TYPE_CLASS_NUMBER);
            Button btn = new Button(TonBagCompletion.this);
            btn.setText("提交");
            btn.setOnClickListener(v -> {
                final EditText remarks = new EditText(TonBagCompletion.this);
                remarks.setHint("若有备注请填写");
                String title = "被记录人："+name;
                new AlertDialog.Builder(this)
                        .setTitle(title)
                        .setView(remarks)
                        .setCancelable(false)
                        .setNegativeButton("取消", ((dialog, which) ->
                                Toast.makeText(TonBagCompletion.this, "取消保存", Toast.LENGTH_SHORT).show()))
                        .setPositiveButton("提交", (dialog, which) ->{
                            // 提交表单
//                            Toast.makeText(TonBagCompletion.this,
//                                    project+" "+tv.getText().toString()+" "+et.getText().toString()+" "+remarks.getText().toString(),
//                                    Toast.LENGTH_LONG).show();
                            RequestQueue queue = Volley.newRequestQueue(this);
                            String url = Config.url + "/sjq/sjqCompletionOfCompostTonbag/add_recorder";
                            StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                                    new Response.Listener<String>() {
                                        @Override
                                        public void onResponse(String response) {
                                            try {
                                                JSONObject jsonObject = new JSONObject(response);
                                                String code = jsonObject.getString("code");
                                                if (code.equals("200"))
                                                    Toast.makeText(TonBagCompletion.this,
                                                            "保存成功", Toast.LENGTH_SHORT).show();
                                                else
                                                    Toast.makeText(TonBagCompletion.this,
                                                            "1保存失败", Toast.LENGTH_SHORT).show();
                                            } catch (JSONException e) {
                                                e.printStackTrace();
                                            }
                                        }
                                    }, new Response.ErrorListener() {
                                @Override
                                public void onErrorResponse(VolleyError error) {
                                    Toast.makeText(TonBagCompletion.this,
                                            "2保存失败 " + error.getMessage(), Toast.LENGTH_SHORT).show();
                                }
                            }) {
                                @Override
                                protected Map<String, String> getParams() {
                                    Map<String, String> map=new HashMap<>();
                                    map.put("recordEntry", project);
                                    map.put("recorder", name);
                                    map.put("value", et.getText().toString());
                                    map.put("remarks", remarks.getText().toString());
                                    map.put("factory", factory);
                                    return map;
                                }
                            };
                            stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                                    DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
                            queue.add(stringRequest);
                            et.clearFocus();
                        })
                        .show();
            });
            ll.addView(tv);
            ll.addView(et);
            ll.addView(btn);

            layout.addView(ll);

            getLatestByProjectAndName(project, name, et);
        }
    }

    private void getLatestByProjectAndName (String project, String name, EditText numInput) {
//        Log.d("zys", project +" "+name);
        RequestQueue queue = Volley.newRequestQueue(this);
        String url = Config.url + "/sjq/sjqCompletionOfCompostTonbag/findByEntryAndOperator";
        StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            String code = jsonObject.getString("code");
                            if (code.equals("200") && !jsonObject.isNull("data")) {
                                JSONObject data = jsonObject.getJSONObject("data");
                                String value = data.getString("value");
                                numInput.setText(value.equals("null") ? "" : value);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(TonBagCompletion.this,
                        "2失败 " + error.getMessage(), Toast.LENGTH_SHORT).show();
            }
        }) {
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> map=new HashMap<>();
                map.put("recordEntry", project);
                map.put("recorder", name);
                map.put("factory", factory);
                return map;
            }
        };
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        queue.add(stringRequest);
    }

    public void show1(View view) {
        if (expandable_1.isExpanded()){
            btn_1.setText("+ 厨余进料未完成量（吨/天）");
        }else{
            btn_1.setText("- 厨余进料未完成量（吨/天）");
        }
        expandable_1.toggle();
    }
    public void show2(View view) {
        if (expandable_2.isExpanded()){
            btn_2.setText("+ 堆肥进料未完成量（个/天）");
        }else{
            btn_2.setText("- 堆肥进料未完成量（个/天）");
        }
        expandable_2.toggle();
    }
    public void show3(View view) {
        if (expandable_3.isExpanded()){
            btn_3.setText("+ 堆肥出料未完成量（个/天）");
        }else{
            btn_3.setText("- 堆肥出料未完成量（个/天）");
        }
        expandable_3.toggle();
    }
    public void show4(View view) {
        if (expandable_4.isExpanded()){
            btn_4.setText("+ 除生料进料配合进、出料（个/天）");
        }else{
            btn_4.setText("- 除生料进料配合进、出料（个/天）");
        }
        expandable_4.toggle();
    }
    public void show5(View view) {
        if (expandable_5.isExpanded()){
            btn_5.setText("+ 厨余岗工作时间外配合进、出吨袋工作时间（小时/天）");
        }else{
            btn_5.setText("- 厨余岗工作时间外配合进、出吨袋工作时间（小时/天）");
        }
        expandable_5.toggle();
    }
    public void show6(View view) {
        if (expandable_6.isExpanded()){
            btn_6.setText("+ 厨余岗进、出吨袋本职工作额外完成量（个/天）");
        }else{
            btn_6.setText("- 厨余岗进、出吨袋本职工作额外完成量（个/天）");
        }
        expandable_6.toggle();
    }
    public void show7(View view) {
        if (expandable_7.isExpanded()){
            btn_7.setText("+ 堆肥岗进料额外完成量（个/天）");
        }else{
            btn_7.setText("- 堆肥岗进料额外完成量（个/天）");
        }
        expandable_7.toggle();
    }
    public void show8(View view) {
        if (expandable_8.isExpanded()){
            btn_8.setText("+ 堆肥岗出料额外完成量（个/天）");
        }else{
            btn_8.setText("- 堆肥岗出料额外完成量（个/天）");
        }
        expandable_8.toggle();
    }
}